package com.cmrx.model.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cmrx.model.entity.User;
import com.cmrx.model.service.LoginService;
import com.cmrx.model.util.ConfigApiReader;
import com.cmrx.model.util.JwtUtil;
import com.cmrx.model.util.LogUtil;
import com.cmrx.model.util.ResultVoUtil;
import com.cmrx.model.vo.IRespCode;
import com.cmrx.model.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("sign")
@Slf4j
@Api(value = "/sign", description = "单点登录相关接口类")
public class SingleSignController {
    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "test", method = RequestMethod.GET)
    @ResponseBody
    public String getTest() {
        return "test";
    }

    @RequestMapping(value = "getToken")
    @ApiOperation(value = "单点登录接口")
    @ApiImplicitParam(name = "map", value = "{\"code\":\"\"}")
    public ResultVo getToken(HttpServletRequest rs) {
//        String code = map.get("code");
//        String resultUrl = ConfigApiReader.getProperty("oauth.url2");
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("client_id", ConfigApiReader.getProperty("client_id"));
//        params.put("client_secret", ConfigApiReader.getProperty("client_secret"));
//        params.put("grant_type", "authorization_code");
//        params.put("redirect_uri", resultUrl);
//        params.put("code", code);

        //获取access_token;由于使用服务端发起http请求，此处访问单点登录服务器不能使用域名；
//        OkHttpClient client = new OkHttpClient();

//        FormBody.Builder builder = new FormBody.Builder();
//        String resultStr = null;
//        for (String key : params.keySet()) {
//            追加表单信息
//            builder.add(key, params.get(key));
//        }

        //请求token
//        try {
//            okhttp3.RequestBody formBody = builder.build();

//            Request request = new Request.Builder()
//                    .url(ConfigApiReader.getProperty("oauth.url1") + "/oauth/token")
//                    .post(formBody)
//                    .build();
//            resultStr = client.newCall(request).execute().body().string();

//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }

        //请求token返回，返回json对象
//        JSONObject accessJson = JSON.parseObject(resultStr);
        String token = "vjdfushbvoguivghvguioiudbhvui";
        String user = "31010619761204162X";
        System.out.println("token:=====" + token);
//        String errorMessage = null;
//        Integer errorCode = 0;
//        if (accessJson != null) {
//            try {
//                if (accessJson.containsKey("access_token")) {
//                    token = accessJson.getString("access_token");
//                }
//                if (accessJson.containsKey("user")) {
//                    user = accessJson.getString("user");
//                }
//                if (accessJson.containsKey("errorMessage")) {
//                    errorMessage = accessJson.getString("errorMessage");
//                }
//                if (accessJson.containsKey("errorCode")) {
//                    errorCode = accessJson.getIntValue("errorCode");
//                }
//
//            } catch (JSONException ex) {
//                ex.printStackTrace();
//            }
//        }

//        String sql = "SELECT t1.ID as userid,t2.TRUE_NAME as userName,t2.ID_CARD_NO as userCard,t2.ID as techid,t3.ORGAN_NAME as organName,t3.REGIONALISM as regionalism FROM sys_user t1 LEFT JOIN technician t2 ON t1.TECH_ID = t2.ID LEFT JOIN organization t3 ON t2.ORGAN_ID = t3.ID WHERE t1.OPEN_FLAG = 1 and t3.OPEN_FLAG = 1 AND t2.ID_CARD_NO = " + user;

        Map<String, String> map1 = new HashMap<>();
//        if (token != null && user != null) {
            map1.put("token", token);
//            System.out.println("user:=================" + user);
            User userLogin = loginService.loginUser(user);
            if (userLogin == null) {
                return ResultVoUtil.error(IRespCode.user_ERR_CODE, IRespCode.user_ERR_msg);
            }
            token = JwtUtil.enToken(userLogin);
            map1.put("userToken", token);
            map1.put("userCard", "31010619761204162X");
//            LogUtil.WriteLogByParam(rs, userLogin, "0", "ID_CARD_NO=" + user, "1", sql);

            System.out.println(map1);
            return ResultVoUtil.success(map1);
//        } else {
//            return ResultVoUtil.error(errorCode, errorMessage);
//        }
    }
}